<template>
  <div class="rule-container">
    <div class="create-container">
      <el-button type="primary" @click="addRule">增加停车计费规则</el-button>
      <el-button @click="exportExcel">导出Excel</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table :data="ruleList" style="width: 100%">
        <el-table-column type="index" label="序号" />
        <el-table-column label="计费规则编号" prop="ruleNumber" />
        <el-table-column label="计费规则名称" prop="ruleName" />
        <el-table-column label="免费时长(分钟)" prop="freeDuration" />
        <el-table-column label="收费上线(元)" prop="chargeCeiling" />
        <el-table-column label="计费方式">
          <template #default="scope">
            {{ formatChargeType(scope.row.chargeType) }}
          </template>
        </el-table-column>
        <el-table-column label="计费规则" prop="ruleNameView" />
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="scope">
            <el-button size="mini" type="text" @click="seeDetail(scope.row.id)">编辑</el-button>
            <el-popconfirm
              title="确定删除吗？"
              @confirm="delRule(scope.row.id)"
            >
              <el-button slot="reference" size="mini" type="text" style="margin-left: 10px;">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <el-pagination
      layout="prev, pager, next"
      :total="total"
      :curren-page="params.page"
      :page-size="params.pageSize"
      @current-change="handlePageChange"
    />
    <!-- 弹框 -->
    <el-dialog :visible="dialogVisible" width="680px" title="新增规则" @close="close">
      <!-- 表单接口 -->
      <div class="form-container">
        <el-form ref="formRef" :model="formData" :rules="rules" label-position="top">
          <el-form-item label="计费规则编号" prop="ruleNumber">
            <el-input v-model="formData.ruleNumber" placeholder="请输入计费规则编号" />
          </el-form-item>
          <el-form-item label="计费规则名称" prop="ruleName">
            <el-input v-model="formData.ruleName" placeholder="请输入计费规则名称" />
          </el-form-item>
          <el-form-item label="计费方式(全天收费)">
            <el-radio-group v-model="formData.chargeType">
              <el-radio border label="duration">时长收费</el-radio>
              <el-radio border label="turn">按次收费</el-radio>
              <el-radio border label="partition">分段收费</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-row type="flex">
            <el-form-item label="免费时长">
              <el-input v-model="formData.freeDuration" class="add-input" size="mini" placeholder="请输入免费时长" /> 分钟
            </el-form-item>
            <el-form-item label="收费上限" style="margin-left:10px">
              <el-input v-model="formData.chargeCeiling" class="add-input" size="mini" placeholder="请输入收费上限" /> 元
            </el-form-item>
          </el-row>
          <!-- 根据类型显示不同 -->
          <el-form-item label="计费规则" prop="chargeType">
            <!-- 按时长收费 -->
            <el-row v-if="formData.chargeType === 'duration'" type="flex" justify="space-between">
              每 <el-input v-model="formData.durationTime" class="input-box" size="mini" placeholder="请输入" /> 小时
              <el-input v-model="formData.durationPrice" class="input-box" size="mini" placeholder="请输入" /> 元
            </el-row>
            <!-- 按次收费 -->
            <el-row v-if="formData.chargeType === 'turn'" type="flex">
              每次 <el-input v-model="formData.turnPrice" class="input-box" size="mini" placeholder="请输入" /> 元
            </el-row>
            <!-- 按分段收费 -->
            <el-row v-if="formData.chargeType === 'partition'">
              <div class="item">
                <el-input v-model="formData.partitionFrameTime" size="mini" class="input-box" placeholder="请输入" />小时内,每小时收费<el-input v-model="formData.partitionFramePrice" size="mini" class="input-box" placeholder="请输入" /> 元
              </div>
              <div class="item">
                每增加<el-input v-model="formData.partitionIncreaseTime" placeholder="请输入" class="input-box" size="mini" />小时,增加<el-input v-model="formData.partitionIncreasePrice" placeholder="请输入" class="input-box" size="mini" /> 元
              </div>
            </el-row>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="close">取消</el-button>
        <el-button size="mini" type="primary" @click="confirmAdd">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { addRuleAPI, deleteRuleAPI, getRuleDetailAPI, getRuleListAPI } from '@/api/car'
import { utils, writeFileXLSX } from 'xlsx'
export default {
  name: 'Building',
  data() {
    return {
      ruleList: [],
      params: {
        page: 1,
        pageSize: 10
      },
      total: 0,
      dialogVisible: false,
      formData: {
        ruleNumber: '',
        ruleName: '',
        freeDuration: '',
        chargeCeiling: null,
        chargeType: 'duration',
        // 时长字段
        durationTime: null,
        durationPrice: null,
        durationType: 'hour',
        // 按次收费
        turnPrice: null,
        // 分段计费
        partitionFrameTime: null, // 段内时间
        partitionFramePrice: null, // 段内费用
        partitionIncreaseTime: null, // 超出时间
        partitionIncreasePrice: null // 超出费为收费价钱
      },
      rules: {
        ruleNumber: [
          { required: true, message: '请输入规则编号', trigger: 'blur' }
        ],
        ruleName: [
          { required: true, message: '请输入规则名称', trigger: 'blur' }
        ],
        chargeType: [
          { required: true, message: '请选择收费类型', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRuleList()
  },
  methods: {
    // 编辑计费规则
    async seeDetail(id) {
      const res = await getRuleDetailAPI(id)
      this.formData = res.data
      this.dialogVisible = true
    },
    // 分页改变
    handlePageChange(page) {
      this.params.page = page
      this.getRuleList()
    },
    async getRuleList() {
      const res = await getRuleListAPI(this.params)
      this.ruleList = res.data.rows
      this.total = res.data.total
    },
    // excel导出 https://docs.sheetjs.com/docs/getting-started/examples/export/
    async exportExcel() {
      // 获取要导出的业务数据
      const res = await getRuleListAPI(this.params)
      // 表头英文字段key
      const tableHeaderKeys = ['ruleNumber', 'ruleName', 'freeDuration', 'chargeCeiling', 'chargeType', 'ruleNameView']
      // 表头中文字段value
      const tableHeaderValues = ['计费规则编号', '计费规则名称', '免费时长(分钟)', '收费上线(元)', '计费方式', '计费规则']
      // 以excle表格的顺序调整后端数据
      const sheetData = res.data.rows.map(item => {
        const obj = {}
        tableHeaderKeys.forEach(key => {
          // 让两个对象相同的key对应同一个value
          if (key === 'chargeType') {
            // 当为计费方式时，格式化一下，不然是英文字母
            obj[key] = this.formatChargeType(item[key])
          } else {
            obj[key] = item[key]
          }
        })
        return obj
      })
      // 创建一个工作表
      const worksheet = utils.json_to_sheet(sheetData)
      // 创建一个新的工作簿
      const workbook = utils.book_new()
      // 把工作表添加到工作簿中
      utils.book_append_sheet(workbook, worksheet, 'Sheet1')
      // 改写表头
      utils.sheet_add_aoa(worksheet, [tableHeaderValues], { origin: 'A1' })
      writeFileXLSX(workbook, '企业信息.xlsx')
    },
    // 适配付费状态，不同于判断语句的方法
    formatChargeType(status) {
      const statusMap = {
        'duration': '时长收费',
        'turn': '按次收费',
        'partition': '分段收费'
      }
      // 利用了对象的键值对，通过键值对进行匹配
      return statusMap[status]
    },
    // 添加计费规则
    async addRule() {
      this.dialogVisible = true
    },
    // 取消添加规则对话框
    close() {
      this.dialogVisible = false
      this.$refs.formRef.resetFields()
      this.formData = {
        ruleNumber: '',
        ruleName: '',
        freeDuration: '',
        chargeCeiling: null,
        chargeType: 'duration',
        // 时长字段
        durationTime: null,
        durationPrice: null,
        durationType: 'hour',
        // 按次收费
        turnPrice: null,
        // 分段计费
        partitionFrameTime: null, // 段内时间
        partitionFramePrice: null, // 段内费用
        partitionIncreaseTime: null, // 超出时间
        partitionIncreasePrice: null // 超出费为收费价钱
      }
    },
    // 确认提交
    async confirmAdd() {
      await this.$refs.formRef.validate()
      await addRuleAPI(this.formData)
      this.$message.success('规则添加成功')
      this.close()
      this.getRuleList()
    },
    // 删除规则
    async delRule(id) {
      await deleteRuleAPI(id)
      this.$message.success('规则删除成功')
      this.getRuleList()
    }
  }
}
</script>

<style lang="scss" scoped>
.rule-container {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}

.form-container .add-input {
  display: inline-block;
  width: 180px;
}

.item {
  display: flex;
}

.input-box {
  flex:1;
  margin: 0 10px;
}

</style>
